package com.snailct.bpp.router.request;

import com.snailct.bpp.commons.protocol.HTTPUtil;
import com.snailct.bpp.commons.protocol.RespResult;
import com.snailct.bpp.commons.utils.SpringContextHolder;
import com.snailct.bpp.commons.xom.castor.XOMTransformerReader;
import com.snailct.bpp.router.IServiceHandler;
import com.snailct.bpp.service.core.definition.DefaultServiceDefinition;
import com.snailct.bpp.service.core.definition.ServiceDefinition;
import com.snailct.bpp.service.core.definition.ServiceType;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by huangxa on 2016/7/13.
 */
public class RemoteServiceHandler implements IServiceHandler {
    private static final Log logger = LogFactory.getLog(RemoteServiceHandler.class);
    public String handleService(ServiceDefinition definition) {
        if(logger.isDebugEnabled()){
            logger.debug("Invoke remote serivce handler!");
        }
        XOMTransformerReader xomTransformerReader = SpringContextHolder.getBean("xomTransformerReader");
        Map<String,String> params = new HashMap<String, String>();
        try {
            params.put("reqData",xomTransformerReader.marshal(definition));
        } catch (IOException e) {
            logger.error("把服务定义对象转换成xml格式出错",e);
            return "ERROR";
        }
        RespResult rtn = null;
        if(definition.getServiceType().equals(ServiceType.WS)){
            CallAWebService webService = new CallAWebService();
            webService.setWsServiceDefinition((DefaultServiceDefinition) definition);
            rtn = webService.sendMessage();
        }else{
            rtn = HTTPUtil.request(params,definition.getServiceAddr());
        }


        if(rtn!=null&&rtn.getStatus().name().equals(RespResult.ReqStatus.OK.name())){
            return rtn.getRtnStr();
        }
        return "ERROR";
    }


}
